<template>
  <a-modal
    title="导出数据"
    width="650px"
    :visible="visible"
    centered
    :maskClosable="false"
    @cancel="handleCancel"
  >
    <template slot="footer">
      <a-button @click="handleCancel">取消</a-button>
      <a-button type="primary" @click="exportExcel">导出</a-button>
    </template>

    <a-form>
      <a-form-item
        label="数据类型"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        :help="typeHelp"
        :validateStatus="typeValidateStatus"
        required
      >
        <a-select v-model="queryParam.typeCode" placeholder="请选择数据类型" @change="typeCodeChange">
          <a-select-option
            v-for="item in dataType"
            :key="item.code"
            :value="item.code"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item
        label="时间范围"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        :help="fieldHelp.time"
        :validateStatus="fieldValidateStatus.time"
        required>
        <a-select v-model="queryParam.timeType" style="width: 90px;margin-right: 10px;" @change="handleTimeTypeChange">
          <a-select-option v-for="type in timeType" :key="type.value">
            {{ type.label }}
          </a-select-option>
        </a-select>

        <span>
          <a-date-picker
            v-model="queryParam.startTime"
            :disabled-date="disabledStartDate"
            :format="time.format"
            :mode="time.mode"
            :placeholder="time.placeholder[0]"
            :open="startOpen"
            @change="startTimeChange"
            @openChange="handleStartOpenChange"
            @panelChange="startTimePanelChange"
            style="margin-right: 10px;"
          />
          <a-date-picker
            v-show="queryParam.timeType != 'year'"
            v-model="queryParam.endTime"
            :disabled-date="disabledEndDate"
            :format="time.format"
            :mode="time.mode"
            :placeholder="time.placeholder[1]"
            :open="endOpen"
            @openChange="handleEndOpenChange"
            @panelChange="endTimePanelChange"
          />
        </span>
      </a-form-item>

      <a-form-item label="区域范围" :labelCol="labelCol" :wrapperCol="wrapperCol">
        <a-cascader
          v-model="queryParam.areas"
          :options="areaOptions"
          :load-data="loadAreaData"
          placeholder="请选择省/市/区县"
          change-on-select
          @change="handleAreaChange"
        />
      </a-form-item>

    </a-form>
  </a-modal>
</template>

<script>
import { baseDataTypeList, exportExcel } from '@/api/modular/main/tsdatarecord/baseDataType'
import { listCity, listProvince, listRegion } from '@/api/modular/main/biindexdata/biIndexDataManage'
import { Cascader } from 'ant-design-vue'
import _ from 'lodash'
export default {
  name: 'ExportForm',
  components: {
    'a-cascader': Cascader
  },
  data() {
    return {
      visible: false,
      queryParam: {},
      dataType: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 }
      },
      currentYear: new Date().getFullYear(),
      timeType: [{ value: 'year', label: '年份' }, { value: 'month', label: '月份' }, { value: 'day', label: '日期' }],
      time: {
        placeholder: [],
        format: '',
        mode: ''
      },
      areaOptions: [],
      endOpen: false,
      startOpen: false,
      typeHelp: '',
      typeValidateStatus: '',
      fieldHelp: {},
      fieldValidateStatus: {},
      areaSelectOptions: [],
      provinceCity: ['北京市', '天津市', '上海市', '重庆市'],
      batchExportLoading: false
    }
  },
  created() {
    this.loadDataType()
    this.loadProvince()
  },
  methods: {
    init() {
      this.queryParam.timeType = 'year'
      this.time = {
        placeholder: ['选择年份', '截止年份'],
        format: 'YYYY',
        mode: 'year'
      }
      this.visible = true
    },
    exportExcel() {
      if (this.queryParam.typeCode === undefined || this.queryParam.typeCode == null) {
        this.typeHelp = '请选择数据类型'
        this.typeValidateStatus = 'error'
        return
      }
      this.$set(this, 'fieldHelp', {})
      this.$set(this, 'fieldValidateStatus', {})
      if (!this.queryParam.startTime) {
        this.$set(this.fieldHelp, 'time', '请选择时间范围')
        this.$set(this.fieldValidateStatus, 'time', 'error')
        return
      }
      const body = {
        typeCode: this.queryParam.typeCode,
        timeType: this.queryParam.timeType
      }
      this.buildTime(body)
      if (this.queryParam.areas) {
        this.buildArea(body)
      }
      this.batchExportLoading = true
      exportExcel(body).then((res) => {
        this.downloadfile(res)
      })
    },
    buildArea(body) {
      if (!this.areaSelectOptions) {
        return
      }
      const _l = this.areaSelectOptions.length
      const province = this.areaSelectOptions[0].label
      if (_l === 1) {
        if (this.provinceCity.indexOf(province) > -1) {
          body.city = province
        } else {
          body.province = province
        }
      }
      if (_l === 2) {
        const city = this.areaSelectOptions[1].label
        if (this.provinceCity.indexOf(province) > -1) {
          body.city = province
        } else {
          body.province = province
          body.city = city
        }
      }
      if (_l === 3) {
        const city = this.areaSelectOptions[1].label
        const region = this.areaSelectOptions[2].label
        if (this.provinceCity.indexOf(province) > -1) {
          body.city = province
        } else {
          body.province = province
          body.city = city
          if (region !== '市辖区') {
            body.region = region
          }
        }
      }
    },
    buildTime(body) {
      let start, end
      if (!this.queryParam.endTime) {
        this.queryParam.endTime = this.queryParam.startTime
      }
      if (this.queryParam.startTime.isSame(this.queryParam.endTime) ||
        this.queryParam.startTime.isBefore(this.queryParam.endTime)) {
        start = this.queryParam.startTime
        end = this.queryParam.endTime
      } else {
        end = this.queryParam.startTime
        start = this.queryParam.endTime
      }
      if (this.queryParam.timeType === 'year') {
        body.start = start.format('YYYY')
        body.end = end.format('YYYY')
      }
      if (this.queryParam.timeType === 'month') {
        body.start = start.format('YYYY-MM')
        body.end = end.format('YYYY-MM')
      }
      if (this.queryParam.timeType === 'day') {
        body.start = start.format('YYYY-MM-DD')
        body.end = end.format('YYYY-MM-DD')
      }
    },

    typeCodeChange() {
      this.typeHelp = ''
      this.typeValidateStatus = 'success'
    },
    disabledStartDate(startValue) {
      const endValue = this.queryParam.endTime
      if (!startValue || !endValue) {
        return false
      }
      return startValue.valueOf() > endValue.valueOf()
    },
    disabledEndDate(endValue) {
      const startValue = this.queryParam.startTime
      if (!endValue || !startValue) {
        return false
      }
      return startValue.valueOf() >= endValue.valueOf()
    },
    startTimeChange(value) {
      console.log('startTimeChange', value)
      this.startOpen = false
    },
    endTimeChange(value) {
      console.log('endTimeChange', value)
      this.endOpen = false
    },
    startTimePanelChange(value, mode) {
      console.log('startTimePanelChange', value)
      this.queryParam.startTime = value
      this.startOpen = false
    },
    endTimePanelChange(value, mode) {
      console.log('endTimePanelChange', value)
      this.queryParam.endTime = value
      this.endOpen = false
    },
    handleStartOpenChange(open) {
      console.log('handleStartOpenChange', this.queryParam)
      this.startOpen = true
      if (!open) {
        this.endOpen = true
      }
    },
    handleEndOpenChange(open) {
      console.log('handleEndOpenChange', this.queryParam)
      this.endOpen = open
    },
    loadDataType() {
      baseDataTypeList().then(res => {
        if (res.success) {
          this.dataType = res.data
        }
      })
    },
    handleTimeTypeChange(value) {
      this.queryParam.startTime = null
      this.queryParam.endTime = null
      if (value === 'year') {
        this.time = {
          placeholder: ['开始年份', '截止年份'],
          format: 'YYYY',
          mode: 'year'
        }
      }
      if (value === 'month') {
        this.time = {
          placeholder: ['开始月份', '截止月份'],
          format: 'YYYY-MM',
          mode: 'month'
        }
      }
      if (value === 'day') {
        this.time = {
          placeholder: ['开始日期', '截止日期'],
          format: 'YYYY-MM-DD',
          mode: 'date'
        }
      }
    },
    loadProvince() {
      listProvince().then(res => {
        this.areaOptions = []
        if (res.success) {
          _.forEach(res.data, d => {
            this.areaOptions.push({
              label: d.name,
              value: d.areaCode,
              isLeaf: false,
              level: d.levelCode
            })
          })
        }
      })
    },
    loadAreaData(selectedOptions) {
      console.log(selectedOptions)
      const targetOption = selectedOptions[selectedOptions.length - 1]
      targetOption.loading = true

      if (targetOption.level === 0) {
        listCity({ proCode: targetOption.value }).then(res => {
          if (res.success) {
            targetOption.children = []
            _.forEach(res.data, d => {
              targetOption.children.push({
                label: d.name,
                value: d.areaCode,
                isLeaf: false,
                level: d.levelCode
              })
            })
            this.areaOptions = [...this.areaOptions]
          }
          targetOption.loading = false
        })
      }
      if (targetOption.level === 1) {
        listRegion({ citCode: targetOption.value }).then(res => {
          if (res.success) {
            targetOption.children = []
            _.forEach(res.data, d => {
              targetOption.children.push({
                label: d.name,
                value: d.areaCode,
                isLeaf: true,
                level: d.levelCode
              })
            })
            this.areaOptions = [...this.areaOptions]
          }
          targetOption.loading = false
        })
      }
    },
    /**
     * 通过返回的元素通过浏览器下载
     * 也就是接受使用这个组件的地方吧下载的内容传过来，
     * 但是这个组件本公子编写的时候只想的适用于导出excel来使用，下载文件呀图片方面的重新整个组件即可
     */
    downloadfile (res) {
      this.batchExportLoading = false
      var blob = new Blob([res.data], { type: 'application/octet-stream;charset=UTF-8' })
      var contentDisposition = res.headers['content-disposition']
      var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
      var result = patt.exec(contentDisposition)
      var filename = result[1]
      var downloadElement = document.createElement('a')
      var href = window.URL.createObjectURL(blob) // 创建下载的链接
      var reg = /^["](.*)["]$/g
      downloadElement.style.display = 'none'
      downloadElement.href = href
      downloadElement.download = decodeURI(filename.replace(reg, '$1')) // 下载后文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() // 点击下载
      document.body.removeChild(downloadElement) // 下载完成移除元素
      window.URL.revokeObjectURL(href)
    },
    handleAreaChange(area, options) {
      this.areaSelectOptions = options
    },
    handleCancel() {
      this.queryParam = {}
      this.typeHelp = ''
      this.typeValidateStatus = ''
      this.visible = false
    }
  }
}
</script>

<style scoped>

</style>
